var userdb = require('../../db/user.db')
var orderdb = require('../../db/order.db')
var async = require('async')
var logger = require('../../logger')
var emit = require('../../emit');

function onsocket(socket, data) {
    async.waterfall([
        (callback) => {
            userdb.getalluser((err, response) => {
                callback(err, response);
            })
        },
        
        (alluser, callback) => {
            var users = new Array();
            async.forEach(alluser, (user, cb) => {
                userdb.getuser(user, (err, u) => {
                    if (err) {
                        cb(err);
                    } else {
                        if (u.active) {
                            u.user = user;
                            users.push(u);
                        }
                        cb(err);
                    }
                })
            }, (err) => {
                callback(err, users);
            });
        },
        (users, callback) => {
            var allorders = {};
            async.forEach(users, (user, cb) => {
                orderdb.getallorders(user.user, (err, orders) => {
                    allorders[user.user] = { user: user, orders: orders };
                    cb(err);
                })
            }, (err) => {
                callback(err, allorders);
            });
        }
    ], (err, allorders) => {
        if (err) {
            logger.log('get all order', err);
            emit.send(socket, "allorder", null);
        } else {
            emit.send(socket, "allorder", allorders);
        }
    });
}

module.exports = {
    onsocket
}